package context.support;

import beans.BeansException;
import beans.factory.config.BeanPostProcessor;
import context.ApplicationContext;
import context.ApplicationContextAware;

/**
 * @Author: Take-off
 * @Description:  Bean 时获取 ApplicationContext 属性，所以需要在执行 refresh 时，
 *             将 ApplicationContext 写入一个包装的 BeanPostProcessor 类中，再使用 AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization 方法调用。
 * @Date: 2023/2/26 2:42 PM
 * @Param
 * @return
 * @Version: 1.0
 **/
public class ApplicationContextAwareProcessor implements BeanPostProcessor {
    private final ApplicationContext applicationContext;

    public ApplicationContextAwareProcessor(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof ApplicationContextAware){
            ((ApplicationContextAware)bean).setApplicationContext(applicationContext);
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}
